﻿public class Solution {
    public int EraseOverlapIntervals(int[][] intervals)
    {
        if (intervals is null || intervals.Length <= 1) return 0;
        
        // 排序
        Array.Sort(intervals, (int[] x, int[] y) =>
        {
            if (x[1].Equals(y[1])) return x[0].CompareTo(y[0]);
            return x[1].CompareTo(y[1]);
        });
        int count = 1; // 记录非交叉区间个数
        int end = intervals[0][1];
        
        for (int i = 1; i < intervals.Length; i++)
        {
            if (end <= intervals[i][0])
            {
                count++;
                end = intervals[i][1];
            }
        }

        return intervals.Length - count;
    }

    public static void Main(string[] args)
    {
        int[][] intervals = [[1, 2], [2, 3], [3, 4], [1, 3]];
        Solution solution = new Solution();
        int res = solution.EraseOverlapIntervals(intervals);
        Console.WriteLine(res);
    }
}